<template>
  <div class="common-project-container">
    <SectionTitle title="分摊费用" style="margin: 32px 0 16px;">
      <div class="total-amount-price">
        <img :src="AmountIcon">总分摊金额：
        <span class="price">{{ getTotalAllocationAmount }}</span>
      </div>
      <div v-if="isEdit" class="options-btn-group">
        <PlainCreateBtn @click="handleAdd">添加</PlainCreateBtn>
      </div>
    </SectionTitle>
    <dynamicEditTable
      ref="dynamicEditTableRef"
      v-model="allocationList"
      :list-data="allocationList"
      :list-setting="listSetting"
      :is-edit="isEdit"
      :show-delete-btn="isEdit"
      :show-serial="false"
      :show-add-btn="false"
      :show-copy-btn="isEdit"
      :extend-btn="extendBtnKey"
      @extendEvent="extendEvent" />
  </div>
</template>

<script>
import { getDepartmentAll } from '@/api/config';
// components
import SectionTitle from '@/components/Title';
import dynamicEditTable from '@/components/Common/dynamicEditTable';
// img
import AmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';

export default {
  components: { SectionTitle, dynamicEditTable },
  model: {
    prop: 'totalAllocationAmount',
    event: 'change'
  },
  props: {
    totalAllocationAmount: {
      type: Number | String,
      default: null
    },
    isEdit: {
      type: Boolean,
      default: true
    },
    showExtendBtn: {
      type: Boolean,
      default: false
    },
    deptTreeList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      AmountIcon,
      allocationList: [{
        deptId: '',
        amount: '',
        desc: ''
      }]
    };
  },
  computed: {
    listSetting() {
      const settingArr = [
        {
          label: '分摊金额(元)',
          type: 'inputNumber',
          width: '150px',
          maxnumber: 999999999,
          isRequired: true,
          isPositiveNumber: true,
          keyword: 'amount',
          placeholder: '请输入'
        }, {
          label: '分摊说明',
          type: 'inputText',
          width: '600px',
          maxlength: 500,
          isRequired: true,
          keyword: 'desc',
          placeholder: '请输入'
        }
      ];
      if (this.isEdit) {
        settingArr.unshift({
          label: '分摊部门',
          type: 'cascader',
          width: '180px',
          keyword: 'deptId',
          keyName: 'id',
          labelName: 'name',
          showAllLevels: false,
          isRequired: true,
          emitPath: false,
          checkStrictly: true,
          options: this.deptTreeList,
          placeholder: '请选择'
        });
      } else {
        settingArr.unshift({
          label: '分摊部门',
          type: 'inputText',
          width: '180px',
          keyword: 'deptName'
        });
      }
      return settingArr;
    },
    getTotalAllocationAmount() {
      if (this.totalAllocationAmount || this.totalAllocationAmount === 0) {
        return this.totalAllocationAmount;
      }
      return '--';
    },
    extendBtnKey() {
      return this.showExtendBtn ? 'desc' : '';
    }
  },
  watch: {
    allocationList: {
      handler(list) {
        this.calculateTotalAmount(list);
      },
      deep: true
    }
  },
  methods: {
    // 获取所属部门
    async queryDeptTreeList() {
      try {
        const result = await getDepartmentAll();
        const list = (result && result.data) || [];
        this.deptTreeList.push(...list);
      } catch (error) {
        console.log(error);
      }
    },
    handleAdd() {
      this.$refs['dynamicEditTableRef'].addValue();
    },
    // 计算总分摊金额
    calculateTotalAmount(list) {
      this.$nextTick(() => {
        let totalAmount = 0;
        list.forEach(item => {
          const amount = item.amount || 0;
          totalAmount += +amount;
        });
        this.$emit('change', totalAmount.toFixed(2));
      });
    },
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs['dynamicEditTableRef'].validate().then(() => {
          resolve();
        }).catch(() => {
          reject();
        });
      });
    },
    extendEvent(data) {
      const extendData = data && data.scope && data.scope.row || {};
      this.$emit('extendEvent', extendData);
    },
    getTableData() {
      return this.allocationList;
    },
    async setTableData(list) {
      if (!this.deptTreeList.length) {
        try {
          await this.queryDeptTreeList();
          this.setAllocationList(list);
        } catch (error) {
          console.log(error);
        }
      } else {
        this.setAllocationList(list);
      }
    },
    setAllocationList(list) {
      if (Array.isArray(list) && list.length) {
        list.forEach(item => {
          const { amount } = item;
          if (amount || amount === 0) {
            item.amount = (+amount).toFixed(2);
          }
        });
      }
      this.allocationList = list;
    }
  }
};
</script>

<style lang="scss" scoped>
.common-project-container {
  &::v-deep {
    .el-select {
      width: 100%;
    }
    .el-cascader--large {
      width: 100%;
    }
    .el-table__body td {
      background-color: #fff !important;
    }
  }
  .total-amount-price {
    display: flex;
    align-items: center;
    background-color: #f8f8f8;
    color: #999;
    font-size: 14px;
    font-weight: normal;
    margin-left: 10px;
    padding: 4px 6px;
    border-radius: 4px;
    > img {
      width: 14px;
      margin-right: 5px;
    }
    .price {
      font-size: 14px;
      color: #406eff;
      font-weight: bold;
    }
  }
  .options-btn-group {
    position: absolute;
    right: 0;
    display: flex;
    align-items: center;
  }
}
</style>
